package cn.com.pc.content.support.util;

import cn.com.pc.content.util.JsonUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author cxh
 */
public class HtmlFilter3 {
	public boolean inTag = false;
	public boolean thumb = true;
	public int bigWidth = 450;
	public StringBuilder buf = new StringBuilder();
	public Map<String, TagHandler> tagHandlerMap;
	private static final Map<String, TagHandler> DEFAULT_TAG_HANDLER_MAP =
			new HashMap<String, TagHandler>();

	private static ThreadLocal<Boolean> trBgColorDark = new ThreadLocal<Boolean>();
	private static ThreadLocal<Boolean> inTable = new ThreadLocal<Boolean>();
	private static ThreadLocal<Boolean> inLive = new ThreadLocal<Boolean>();
	private static ThreadLocal<Boolean> thumbImg = new ThreadLocal<Boolean>();
	private static ThreadLocal<Boolean> inScript = new ThreadLocal<Boolean>();

	private static String siteName = "pconlie";//可变化

	public HtmlFilter3() {
	}

	public HtmlFilter3(boolean thumb, int bigWidth) {
		this.thumb = thumb;
		this.bigWidth = bigWidth;
	}

	public void setTagHandlerMap(Map<String, TagHandler> tagHandlerMap) {
		this.tagHandlerMap = tagHandlerMap;
	}

	public String process(String html) {
		return process(html, DEFAULT_TAG_HANDLER_MAP);
	}

	public String process(String html, Map<String, TagHandler> tagHandlerMap) {
		this.tagHandlerMap = tagHandlerMap;
		int start = 0;
		int len = html.length();
		thumbImg.set(thumb);
		trBgColorDark.set(false);
		inTable.set(false);
		inLive.set(false);
		inScript.set(false);
		for (int i = 0; i < len; i ++) {
			char ch = html.charAt(i);
			switch (ch) {
				case '<':
					int c = handle(html, start, i);

					// process html comment
					if (i + 6 < len) {
						if (html.charAt(i + 1) == '!'
								&& html.charAt(i + 2) =='-'
								&& html.charAt(i + 3) =='-') {
							int pos = html.indexOf("-->", i + 4);

							String comment = html.substring(i + 4, pos);
							if(comment.startsWith("_MROBOT_MARK_") && comment.endsWith("_MROBOT_MARK_")){
								buf.append(html.substring(i + 17, pos - 13)); //'_MROBOT_MARK_'(13),'<!--'(4)
							}

							if (pos != -1) {
								i = pos + 3;
								start = i;
//                                i--;
								break;
							}
						}
					}

					if (c == 0) {
						start = i;
					} else {
						start = c;
						i = start - 1;
					}
					inTag = true;
					break;
				case '>':
					int d = handle(html, start, i);
					if (d == 0) {
						start = i + 1;
					} else {
						start = d;
						i = start - 1;
					}
					inTag = false;
					break;
				default:
					break;
			}
		}

		handle(html, start, len);

		trBgColorDark.remove();
		inTable.remove();
		thumbImg.remove();
		inLive.remove();
		inScript.remove();
		return buf.toString();

	}

	public int handle(String html, int start, int end) {
		if (inTag) {
			if (tagHandlerMap != null) {
				Tag tag = new Tag(html.substring(start, end + 1));
				TagHandler handler = tagHandlerMap.get(tag.getName());
				boolean begin = tag.isBegin();
				if (handler != null) {
					int handleRet = handler.handle(buf, tag, begin);
					if (handleRet > 0 && begin) {
						String tagEnd = "</" + html.substring(start + 1, start + 1 + tag.getName().length()) + '>';
						int pos = html.indexOf(tagEnd, end);
						if (pos != -1) {
							if (handleRet == 2) {
								String s = html.substring(start, pos + tagEnd.length());
								if(s.indexOf("[time]")!=-1){
									buf.append(s.replaceAll("(?i)<img", "<IMG class=\"tabimg\""));
								}else{
									buf.append(s.replaceAll("(?i)<img", "<IMG class=\"tabimg\"")
											.replaceAll("(i)<a", "<a onclick='if(event)event.stopPropagation();'"));
								}
							}else if(handleRet == 5){//处理v3接口，过滤调查代码form表单的内容
								String s = html.substring(start, pos + tagEnd.length());
								Pattern pattern3 = Pattern.compile("<form.*?action=[\"|\'](.*?\\/\\/)survey[.](.*?)[\"|\']>([\\s\\S]*?)</form>");
								Matcher m=pattern3.matcher(s);
								if(m.find()){
									String site = "pconline";//这里根据网站来的
									if("pconline".equalsIgnoreCase(site)){//电脑网会有多个form表单，添加surveyId值便于匹配
										Pattern surveyIdPattern = Pattern.compile("<input.*?name=[\"|\'](id)[\"|\'][^\\/]*value=[\"|\'](\\d*)[\"|\']\\s*[\\/>|>]*");
										String subStr = m.group(3);
										Matcher m2 = surveyIdPattern.matcher(subStr);
										if(m2.find()){
											String surveyId = m2.group(2);
											s = s.replace(subStr, "").replace("></form>", " tpid=\"" + surveyId + "\" ></form>");
										}else{
											s = s.replace(m.group(3), "");
										}
										s = s.replace("submit.jsp", "submitByApp.jsp");
										buf.append(s);
									}else{
										s = s.replace(m.group(3), "");
										s = s.replace("submit.jsp", "submitByApp.jsp");//替换成app提交
										buf.append(s);
									}
								}
							}else if(handleRet == 3){
								int ee = html.indexOf('>', start);
								//buf.append(html.substring(ee+1, pos + tagEnd.length()).replaceAll("(i)<a", "<a onclick='if(event)event.stopPropagation();'"));
								String content = html.substring(ee+1, pos + tagEnd.length() - 4);
								if(content.toLowerCase().contains("<img")){
									buf.delete(buf.lastIndexOf("<a"), buf.length());
									buf.append(content.replaceAll("(?i)<img ", "<IMG class=\"tabimg\""));
								}else{
									buf.append(content.replaceAll("<a", "<a onclick='if(event)event.stopPropagation();'"));
									buf.append("</a>");
								}
							}else if(handleRet == 4){
								int ee = html.indexOf('>', start);
								String content = html.substring(ee+1, pos + tagEnd.length() - 4);
								if(content.toLowerCase().contains("<img")){//图片链点开放
									int index=buf.toString().lastIndexOf("<a");
									if (index!=-1){
										String href = buf.toString().substring(index).replaceAll("<a([^>]*) href='([^']*)'([^>]*)>", "$2");
										//mrobot要求，图片链点要带上http协议
										href = HtmlCMSUtils.replaceHttpUrl(href);
										buf.delete(buf.lastIndexOf("<a"), buf.length());
										buf.append(content.replaceAll("(?i)<img ", "<IMG class=\"imgLink\" onclick=\"location.href = '"+href+"';\" "));
									}else{
										buf.delete(buf.lastIndexOf("<a"), buf.length());
										buf.append(content.replaceAll("(?i)<img ", "<IMG class=\"tabimg\""));
									}
								}else  if(content.toLowerCase().replaceAll("(?si)<\\s*[\\w|/][^>]*>", "").trim().matches("\\/\\/(\\w+).(pconline|pcauto).com.cn\\/.*?(\\d+)\\/(\\d+)\\.html")){   //汽车相关文章url链点转为图片链点
									int index=buf.toString().lastIndexOf("<a");
									if (index!=-1){
										String ahref = buf.toString().substring(index).replaceAll("(<a([^>]*) class=')([^']*)('([^>]*)>)", "$1relaLink$4");
										buf.delete(buf.lastIndexOf("<a"), buf.length());
										buf.append(ahref);
										content= "网页链接";
										buf.append(content);
										buf.append("</a>");
									}else{
										buf.append(content.replaceAll("(i)<a", "<a onclick='if(event)event.stopPropagation();'"));
										buf.append("</a>");
									}
								}else{
									buf.append(content.replaceAll("(i)<a", "<a onclick='if(event)event.stopPropagation();'"));
									buf.append("</a>");
								}
							}else if(handleRet == 6){//游戏网/电脑网外链
								int ee = html.indexOf('>', start);
								String content = html.substring(ee+1, pos + tagEnd.length() - 4);
								if(content.toLowerCase().contains("<img")){
									buf.delete(buf.lastIndexOf("<a"), buf.length());
									return 0;
								}
								buf.append(content);
								buf.append("</a>");
							} else if(handleRet == 7){
								String musicUrl = tag.getAttr("musicurl");
								String autoPlay = tag.getAttr("autoplay");
								String orgFileName = tag.getAttr("orgfilename");
								if(musicUrl != null){
									/*转化后结构
									 * <div class='m-audio' id='PlayA'></div>
									 * <script type='text/javascript' src='http://js.3conline.com/wap/pconline/2015/cms/js/audio_zj.js'></script>
									 * <script type="text/javascript">
									 *	var audioA= new audio_zj();
									 *	audioA.init(document.querySelector("#PlayA"),"http://www1.pconline.com.cn/gqye/2015/audio/song/42592062.mp3","隔墙有耳第一期.MP3",'(auto|normal)');
									 *	</script>
									 */
									try {
										Thread.sleep(1l);//休眠1毫秒，确保id不同
									} catch (InterruptedException e) {
									}
									long id = System.currentTimeMillis();
									if(buf.toString().indexOf("2015/cms/js/audio_zj.js")==-1)
										buf.append("<script type='text/javascript' src='http://js.3conline.com/wap/pconline/2015/cms/js/audio_zj.js'></script>");
									buf.append("<div class='m-audio' id='Play_"+id+"'></div>")
											.append("<script type='text/javascript'>")
											.append("var audio_"+id+"= new audio_zj();")
											.append("audio_"+id+".init(document.querySelector('#Play_"+id+"'),'").append(musicUrl).append("','").append(orgFileName).append("'")
											.append(",'").append("true".equals(autoPlay) ? "auto" : "normal").append("'")
											.append(");")
											.append("</script>");
								}
							} else if (handleRet == 8) {//汽车网相关文章结构替换
								String s = html.substring(start, pos + tagEnd.length());
								buf.append(HtmlCMSUtils.changeRelateAet(s, "mrobot"));
							} else if (handleRet == 9) { //修改车型参数表格
                        	    /*String s = html.substring(start, pos + tagEnd.length());
                        	    String carIds = tag.getAttr("iscarparameter");
	                        	//截取表格的tr内容
	                  	    	List<String> trList = new ArrayList<String>();
	                  	    	String trRegx = "(?i)<tr[^>]*?>([\\s\\S]*?)</tr[^>]*?>";
	                  	    	Pattern pattern = Pattern.compile(trRegx);
	                  	    	Matcher trMatch = pattern.matcher(s);
	                  	    	while (trMatch.find()){
	                  	    		trList.add(trMatch.group(1));
	                  	    	}
	                  	    	//开始拼接新的表格
	                  	    	buf.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"1\" class=\"priceConfig_simple\">")
	                  	    	      .append("<tbody>")
	                  	    	      .append("<tr class=\"priceConfigTit\"><td colspan=\""+(carIds.split(",").length+1)+"\" height=\"35\">车型参配对比</td></tr>");
	                  	    	for(int i=0;i<trList.size();i++){
	                  	    		String tr = trList.get(i);
	                  	    		if(tr.contains(">车型图片：<")){
                  	    				String regx = "(?i)\\ssrc=(.*?)\\s";
                  	    		    	Pattern p = Pattern.compile(regx);
                  	    		    	Matcher match = p.matcher(tr);
                  	    		    	while (match.find()){
                  	    		    		String src = match.group(1);
                  	    		    		tr  = tr.replaceFirst("src="+src, "src=\"http://www1.pcauto.com.cn/wap/2013/cms/img/loading.png\" src2="+src);
                  	    		    	}
	                  	    			buf.append("<tr>").append(tr.replaceFirst("<.*?>", "<td class='th'><em>").replaceFirst("</.*?>", "</em></td>").replaceAll("target=\"_blank\"", "").replaceAll("</?a.*?>", "").replaceAll("height=\"90\"", "").replaceAll("width=\"120\"", "")).append("</tr>");
	                  	    		}else if(tr.contains(">车型信息：<")){
	                  	    			buf.append("<tr>").append(tr.replaceFirst("<.*?>", "<td class='th'><em>").replaceFirst("</.*?>", "</em></td>").replaceAll("target=\"_blank\"", "").replaceAll("</?strong>", "").replaceAll("<br/>", "").replaceAll("<a href=.*?>","").replaceAll("</a>","").replaceAll("车型信息：", "车型")).append("</tr>");
	                  	    		}else if(tr.contains(">官方价：<")||tr.contains(">厂商：<")||tr.contains(">发动机：<")||tr.contains(">变速箱：<")){
	                  	    			buf.append("<tr>").append(tr.replaceFirst("<.*?>", "<td class='th'><em>").replaceFirst("</.*?>", "</em></td>").replaceAll("target=\"_blank\"", "").replaceAll("</?strong>", "").replaceAll("<br/>", "").replaceAll("：", "")).append("</tr>");
	                  	    		}
	                  	    	}
	                  	    	buf.append("<tr class='priceConfigMore'>")
	                  	    		.append("<td colspan='"+(carIds.split(",").length+1)+"' height='35'><a href='pcaction://serial-list-pk?carIds=["+carIds+"]'>查看全部参数&nbsp;&gt;</a></td></tr>");
	                  	    	buf.append("</tbody></table>");*/

								String s = html.substring(start, pos + tagEnd.length());
								String carIds = tag.getAttr("iscarparameter");
								//截取表格的tr内容
								List<String> trList = new ArrayList<String>();
								String trRegx = "(?i)<tr[^>]*?>([\\s\\S]*?)</tr[^>]*?>";
								Pattern pattern = Pattern.compile(trRegx);
								Matcher trMatch = pattern.matcher(s);
								while (trMatch.find()){
									trList.add(trMatch.group(1));
								}
								//开始拼接新的表格
								buf.append("<table class=\"m-table m-paramCompare\">")
										.append("<tbody><tr><th colspan=\""+(carIds.split(",").length+1)+"\"><span class=\"th\">车型参配对比</span></th></tr>");
								for(int i=0;i<trList.size();i++){
									String tr = trList.get(i);
									if(tr.contains(">车型图片：<")){
	                  	    			/*String regx = "href=\"(.*?)\"";
                  	    		    	Pattern p = Pattern.compile(regx);
                  	    		    	Matcher match = p.matcher(tr);
                  	    		    	while (match.find()){
                  	    		    		String href = match.group(1);
                  	    		    		tr  = tr.replace(match.group(0), " onclick='if(event)event.stopPropagation();' href='"+HtmlCMSUtils.getPcautoBrowser(href)+"'");
                  	    		    	}*/
										tr = tr.replaceAll("(?i)<a[\\s\\S^>]*?>", "").replaceAll("(?i)</a[\\s\\S^>]*?>", "");
										buf.append("<tr>").append(tr.replaceFirst("<td.*?>车型图片：</td>", "<td class=\"s-gray7\">车型图片</td>").replaceAll("<td\\sclass=\"tb\">", "<td class=\"m-pic\">").replaceAll("target=\"_blank\"", "class=\"pic\"")
												.replaceAll("height=\"\\d*?\"", "class=\"s-place\"").replaceAll("width=\"\\d*?\"", "").replaceAll("<img", "<IMG")).append("</tr>");
									}else if(tr.contains(">车型信息：<")){
										String regx = "href=\"(.*?)\"";
										Pattern p = Pattern.compile(regx);
										Matcher match = p.matcher(tr);
										while (match.find()){
											String href = match.group(1);
											tr  = tr.replace(match.group(0), " onclick='if(event)event.stopPropagation();' href='"+ HtmlCMSUtils.getPcautoBrowser(href)+"'");
										}
										buf.append("<tr>").append(tr.replaceFirst("<td.*?>车型信息：</td>", "<td class=\"s-gray7\">车型</td>").replaceAll("class=\"tb\"", "").replaceAll("target=\"_blank\"", "class=\"s-blue\"").replaceAll("<br/>", "").replaceAll("</?strong>", "")).append("</tr>");
									}else if(tr.contains(">官方价：<")){
										buf.append("<tr>").append(tr.replaceFirst("class=\"th\"", "class=\"s-gray7\"").replaceAll("class=\"tb\"", "class=\"s-red\"").replaceAll("：<", "<")).append("</tr>");
									}else if(tr.contains(">厂商：<")||tr.contains(">发动机：<")||tr.contains(">变速箱：<")){
										buf.append("<tr>").append(tr.replaceFirst("<tr.*?>", "<tr>").replaceFirst("class=\"th\"", "class=\"s-gray7\"").replaceAll("class=\"tb\"", "").replaceAll("：<", "<")).append("</tr>");
									}
								}
								buf.append("<tr>").append("<td colspan=\""+(carIds.split(",").length+1)+"\"><a href=\"pcaction://serial-list-pk?carIds=["+carIds+"]\" class=\"btn-more s-blue\">查看全部参数<i class=\"u-arr u-arr-r\"></i></a></td></tr></tbody></table>");

							} else if (handleRet == 10) { //修改js2

								int index = html.indexOf(">立即下载</a></div></div>", start);
								if(index > -1){
									String s = html.substring(start, index + ">立即下载</a></div></div>".length());
									Matcher nameMatcher = Pattern.compile("title=\"(.*?)\">").matcher(s);
									String name = nameMatcher.find()?nameMatcher.group(1):"";
									Matcher logoMatcher = Pattern.compile("<img height=\"100\"\\sid=\"logo\"\\ssrc=\"(.*?)\"\\s").matcher(s);
									String logo = logoMatcher.find()?logoMatcher.group(1):"";
									Matcher sizeMatcher = Pattern.compile("</em><span\\sid=\"softSize\">(.*?)</span></li>").matcher(s);
									String size = sizeMatcher.find()?sizeMatcher.group(1):"";
									Matcher urlMatcher = Pattern.compile("</em><span><a\\shref=\"(.*?)\"\\sid=\"softDLUrl\"\\s").matcher(s);
									String url = urlMatcher.find()?urlMatcher.group(1):"";
									buf.append("<p><span class=\"softjs\">");
									buf.append("<a href=\""+url+"\" target=\"_blank\">");
									buf.append("<img src=\""+logo+"\" class=\"softjs-logo\" data-width=\"0\" data-height=\"0\">");
									buf.append("<span class=\"softjs-txt\">");
									buf.append("<span class=\"softjs-name\">"+name+"</span>");
									buf.append("<span class=\"softjs-info\">软件大小："+size+"</span>");
									buf.append("</span><span class=\"softjs-btn\">下载</span></a></span></p>");

									return index + ">立即下载</a></div></div>".length();
								}
							} else if (handleRet == 11) { //修改js3

								int index = html.indexOf(">立即下载</a></div></li></ul></div></div>", start);
								if(index > -1){
									String s = html.substring(start, index + ">立即下载</a></div></li></ul></div></div>".length());
									Matcher serialMatcher = Pattern.compile("<div\\sclass=\"softjs3-hd\">(.*?)</div>").matcher(s);
									String title = serialMatcher.find()?serialMatcher.group(1):"";
									List<Map<String, String>> liList = new ArrayList<Map<String, String>>();
									Matcher liMatcher = Pattern.compile("<li>([\\s\\S]*?)</li>").matcher(s);
									String li = "";
									while(liMatcher.find()){
										li = liMatcher.group(1);
										Matcher nameMatcher = Pattern.compile("<div\\sclass=\"softjs3-name\"><a[\\s\\S]*?>(.*?)</a></div>").matcher(li);
										String name = nameMatcher.find()?nameMatcher.group(1):"";
										Matcher logoMatcher = Pattern.compile("<a\\sclass=\"softjs3-logo\"[\\s\\S]*?src=\"(.*?)\"\\swidth=\"40\"/></a>").matcher(li);
										String logo = logoMatcher.find()?logoMatcher.group(1):"";
										Matcher sizeMatcher = Pattern.compile("<div\\sclass=\"softjs3-size\"\\sstyle=\"display:none\">(.*?)</div>").matcher(li);
										String size = sizeMatcher.find()?sizeMatcher.group(1):"";
										Matcher urlMatcher = Pattern.compile("<div\\sclass=\"softjs3-dl\"><a\\shref=\"(.*?)\"\\starget=\"_blank\">立即下载</a></div>").matcher(li);
										String url = urlMatcher.find()?urlMatcher.group(1):"";
										Map<String, String> liMap = new HashMap<String, String>();
										liMap.put("name", name);
										liMap.put("logo", logo);
										liMap.put("size", size);
										liMap.put("url", url);
										liList.add(liMap);
									}
									buf.append("<p><span class=\"softjs\"><span class=\"softjs-hd\">"+title+"</span><span class=\"softjs-bd\">");
									for(int i=0;i<liList.size();i++){
										Map<String, String> map = liList.get(i);
										buf.append("<span class=\"softjs-item\">");
										buf.append("<a href=\""+map.get("url")+"\" target=\"_blank\">");
										buf.append("<img src=\""+map.get("logo")+"\" class=\"softjs-logo\" data-width=\"0\" data-height=\"0\">");
										buf.append("<span class=\"softjs-txt\">");
										buf.append("<span class=\"softjs-name\">"+map.get("name")+"</span>");
										buf.append("<span class=\"softjs-info\">"+map.get("size")+"</span>");
										buf.append("</span><span class=\"softjs-btn\">下载</span></a></span>");
									}
									buf.append("</span></span></p>");

									return index + ">立即下载</a></div></li></ul></div></div>".length();
								}
							}else if (handleRet == 12){//图文描述结构转换
								String s = html.substring(start, pos + tagEnd.length());
								Matcher srcMatcher = Pattern.compile("\\ssrc=\"(.*?)\"\\s").matcher(s);
								String src = "";
								while(srcMatcher.find()){
									src = srcMatcher.group(1);
								}
								Matcher descMatcher = Pattern.compile("</i>(.*?)</span>").matcher(s);
								String desc = descMatcher.find()?descMatcher.group(1):"";
								//拿出图片的长和宽
								Matcher heightAndWidthMat = Pattern.compile("\\sdata-height=\"(\\d+?)\"\\sdata-width=\"(\\d+?)\"").matcher(s);
								String height = "0";
								String width = "0";
								if(heightAndWidthMat.find()){
									height = heightAndWidthMat.group(1);
									width = heightAndWidthMat.group(2);
								}
								if(!"".equals(src)){
									buf.append("<div class=\"block\">");
									//buf.append("<div id=\"img_1\" style=\"position: relative; width: 100%; margin: 0 auto;\">");
									//buf.append("<img class=\"bigimg\" src=\""+src+"\" onclick=\"getAllImg('"+src+"'); if(event) event.stopPropagation();\"/>");
									//mrobot要求图片url都要加http协议
									src = HtmlCMSUtils.replaceHttpUrl(src);
									buf.append("<img class=\"bigimg\" onclick=\"viewPic(this, event);\" src=\""+src+"\" data-height=\""+height+ "\" data-width=\""+width+"\" />");
									//buf.append("</div>");
									if(!"".equals(desc)){
										desc = desc.replaceAll("<a[^>]*?>", "").replaceAll("</a>", "");
										buf.append("<div class=\"m-des\">"+desc+"</div>");
									}
									buf.append("</div>");
								}else{
									buf.append(s);
								}

							}else if (handleRet == 13){//图片参配信息转换

								buf.append("<div class=\"m-art-seria-wrap\">");
								//先替换了图片样式
								String picString = html.substring(start, pos + tagEnd.length());
								String newPicString = change4Pic(picString);
								buf.append(newPicString);
								//拼接参配结构
								int paramStart = pos + tagEnd.length();
								int curryParam =  pos + tagEnd.length();
								String flag = "artPriPort";
								int tables = 0;//后面带多少个table结构
								boolean breakFlag = true;
								while (breakFlag) {
									int paramPos = html.indexOf(flag, curryParam + 1);
									if (paramPos > 0 && paramPos - curryParam <= 38) {//下一个table标识位置不能超过38个长度
										tables ++;
										curryParam = html.indexOf(tagEnd, paramPos + 10); //寻找下一个时候加artPriPort
									} else {
										breakFlag = false;
									}
									//最多五层退出
									if (tables >= 5 && pos < 0) {
										breakFlag = true;
									}
								}
								if (curryParam > 0 && tables > 0) {
									String picTable = html.substring(paramStart, curryParam + tagEnd.length());
									//替换新的图片表格
									if (StringUtils.isNotBlank(picTable)) {
										String newPicTable = change4PicTable(picTable);
										buf.append(newPicTable);
										pos = curryParam;
									}
								}
								buf.append("</div>");
							}else if (handleRet == 131){//图片参配信息转换 180601 新版

								buf.append("<div class=\"m-art-seria-wrap\">");
								//先替换了图片样式
								String picString = html.substring(start, pos + tagEnd.length());
								String newPicString = change4Pic2(picString);
								buf.append(newPicString);
								//拼接参配结构
								int paramStart = pos + tagEnd.length();
								int curryParam =  pos + tagEnd.length();
								String flag = "artPriPort";
								int tables = 0;//后面带多少个table结构
								boolean breakFlag = true;
								while (breakFlag) {
									int paramPos = html.indexOf(flag, curryParam + 1);
									if (paramPos > 0 && paramPos - curryParam <= 38) {//下一个table标识位置不能超过38个长度
										tables ++;
										curryParam = html.indexOf(tagEnd, paramPos + 10); //寻找下一个时候加artPriPort
									} else {
										breakFlag = false;
									}
									//最多五层退出
									if (tables >= 5 && pos < 0) {
										breakFlag = true;
									}
								}
								if (curryParam > 0 && tables > 0) {
									String picTable = html.substring(paramStart, curryParam + tagEnd.length());
									//替换新的图片表格
									if (StringUtils.isNotBlank(picTable)) {
										String newPicTable = change4PicTable2(picTable);
										buf.append(newPicTable);
										pos = curryParam;
									}
								}
								buf.append("</div>");
							}else if (handleRet == 14){//点评表格转换
								String s = html.substring(start, pos + tagEnd.length());
								String editor = "";
								String carId = "";
								String carName = "";
								String summary = "";
								String advantage = "";
								String weakness = "";
								String editorReg = "<strong\\sclass=\"fr\">(.*?)</strong>";
								Matcher editorMat = Pattern.compile(editorReg).matcher(s);
								if (editorMat.find()) {
									editor = editorMat.group(1);
								}
								String carReg = "<p\\sclass=\"carType\"><a\\shref=.*?/m(\\d+?)/\".*?>(.*?)</a></p>";
								Matcher carMat = Pattern.compile(carReg).matcher(s);
								if (carMat.find()) {
									carId = carMat.group(1);
									carName = carMat.group(2);
								}
								String summaryReg = "<p><strong>整体评价：</strong>(.*?)</p>";
								Matcher summaryMat = Pattern.compile(summaryReg).matcher(s);
								if (summaryMat.find()) {
									summary = summaryMat.group(1);
								}
								String regex2 = "<td\\sclass=\"evaluationTableColA\">([\\s\\S]*?)</td>"+
										"<td\\sclass=\"evaluationTableColB\">([\\s\\S]*?)</td></tr></tbody></table>";
								Matcher matcher2 = Pattern.compile(regex2).matcher(s);
								if(matcher2.find()){
									advantage = matcher2.group(1);
									weakness = matcher2.group(2);
								}
								buf.append("<table class=\"m-table m-comment\"><tbody>");
								buf.append("<tr><th colspan=\"2\"><span class=\"th f-fl\">编辑点评</span><i class=\"name f-fr\">"+editor+"</i></th></tr>");
								if(!StringUtils.isBlank(carId) && !StringUtils.isBlank(carName)) {
									buf.append("<tr><td colspan=\"2\"><a class=\"carType s-blue\" onclick=\"if(event)event.stopPropagation();\" href=\""+ HtmlCMSUtils.getPcautoBrowser("http://price.pcauto.com.cn/m"+carId+"/")+"\">"+carName+"</a></td></tr>");
								}
								if(!"".equals(advantage) || !"".equals(weakness)){
									buf.append("<tr class=\"row-divide\">");
									buf.append("<td><p class=\"des\"><em>优点</em>");
									Matcher advMatcher = Pattern.compile("<dd>(.*?)</dd>").matcher(advantage);
									while(advMatcher.find()){
										buf.append("<span>"+advMatcher.group(1)+"</span>");
									}
									buf.append("</p></td><td><p class=\"des\"><em>缺点</em>");
									Matcher weakMatcher = Pattern.compile("<dd>(.*?)</dd>").matcher(weakness);
									while(weakMatcher.find()){
										buf.append("<span>"+weakMatcher.group(1)+"</span>");
									}
									buf.append("</p></td></tr>");
								}
								buf.append("<tr><td colspan=\"2\"><p class=\"des\"><em>整体评价</em>");
								buf.append("<span>"+summary+"</span>");
								buf.append("</p></td></tr></tbody></table>");
							}else if (handleRet == 15) {//替换车型库报价表格
								//因为有两个table，获取第二个table的结束位置
								int twoPos = html.indexOf(tagEnd, pos+1);
								if (twoPos != -1) {
									//截取原来行情结构
									String hqTable = html.substring(start, twoPos + tagEnd.length());
									//修改wap行情结构
	                        		/*//去掉底部车系频道，制表：太平洋汽车网
	                        		hqTable = hqTable.replaceAll("<tr><td\\sclass=\"loan\"\\scolspan=\"\\d+?\"\\sheight=\"\\d+?\"><table\\sclass=\"priTableBtm\">[\\s\\S]*?</table></td></tr>", "");
	                        		//去掉车贷列
	                        		hqTable = hqTable.replaceAll("<td\\salign=\"center\"\\sclass=\"loan\"><p class=\"(priTableColF|priTableThF)\">[\\s\\S]*?</p></td>", "");
	                        		//修改a标签跳转链接
	                        		String regex = "<a.*?href=\"(.*?)\".*?>";
	                        		Matcher matcher = Pattern.compile(regex).matcher(hqTable);
	                        		while(matcher.find()){
	                        			hqTable = hqTable.replace(matcher.group(0),
	                        					"<a  class='rlink' onclick='if(event)event.stopPropagation();' href='"+HtmlCMSUtils.getPcautoBrowser(matcher.group(1))+"'>");
	                        		}
	                        		buf.append(hqTable);
	                        		pos = twoPos;*/
									String newHqTable = change4hqTable(tag, hqTable);
									buf.append(newHqTable);
									pos = twoPos;
								}
							}else if (handleRet == 16) {//替换可选分类参数表格
								String s = html.substring(start, pos + tagEnd.length());
								String title = "";
								Matcher titleMatcher = Pattern.compile("<th\\sclass=\"configTableTit\".*?><strong>(.*?)</strong></th>").matcher(s);
								title = titleMatcher.find()?titleMatcher.group(1):"";
								//拿出车系、车系ID、车型、车型ID
								Matcher carsMatcher = Pattern.compile(
										"<p\\sclass=\"carMsg\">[^<]*?<a\\shref=\".*?\\/sg(\\d*?)\\/\".*?>(.*?)</a>[^<]*?<br/>[^<]*?<a\\shref=\".*?\\/m(\\d*?)\\/\".*?>(.*?)</a>[^<]*?</p>").matcher(s);
								List<String> carsList = new ArrayList<String>();
								while(carsMatcher.find()){
//                        		  System.out.println("___________车系ID:"+carsMatcher.group(1)+",车系："+carsMatcher.group(2)+",车型ID:"+carsMatcher.group(3)+",车型:"+carsMatcher.group(4));
									carsList.add(carsMatcher.group(1)+"~_~"+carsMatcher.group(2)+"~_~"+carsMatcher.group(3)+"~_~"+carsMatcher.group(4));
								}

//                        	  boolean isA = false;
//                        	  boolean isB = false;
//                        	  boolean isC = false;
								boolean isTip = false;
								if(s.indexOf("<span>● 标配</span><span>○ 选配</span><span>- 无</span>")!=-1){
									isTip = true;
								}

								String carIds = "";
								//拿出每一项配置
								Matcher trMatcher = Pattern.compile("<tr>([\\s\\S]*?)</tr>").matcher(s);
								List<List<String>> trList = new ArrayList<List<String>>();
								Pattern tdPattern = Pattern.compile("<td\\sclass=\"configTableCol.\".*?>(.*?)</td>");
								while(trMatcher.find()){
									Matcher tdMatcher = tdPattern.matcher(trMatcher.group(1));
									List<String> list = new ArrayList<String>();
									while(tdMatcher.find()){
										String tdContent = tdMatcher.group(1);
										list.add(tdContent);
//                        			  if(!isA && "●".equals(tdContent)){
//                        				  isA = true;
//                        			  }
//                        			  if(!isB && "○".equals(tdContent)){
//                        				  isB = true;
//                        			  }
//                        			  if(!isC && "-".equals(tdContent)){
//                        				  isC = true;
//                        			  }
									}
									trList.add(list);
								}
								//开始拼接
								buf.append("<table class=\"m-table m-param\"><tbody><tr><th colspan=\""+(carsList.size()+1)+"\"><span class=\"th\">"+title+"</span></th></tr>");
								if(isTip){
									buf.append("<tr><td colspan=\""+(carsList.size()+1)+"\" class=\"tit s-gray7\"><div class=\"m-submk\">");
									buf.append("<i>● 标配</i>");
									buf.append("<i>○ 选配</i>");
									buf.append("<i>- 无</i>");
									buf.append("</div></td></tr>");
								}
								buf.append("<tr><td class=\"s-gray7\">车型</td>");
								for(String carConf : carsList){
									String carsConfig[] = carConf.split("~_~");
									buf.append("<td><a onclick='if(event)event.stopPropagation();' href=\""+ HtmlCMSUtils.getPcautoBrowser("http://price.pcauto.com.cn/m"+carsConfig[2]+"/")+"\" class=\"s-blue\">"+carsConfig[1]+carsConfig[3]+"</a></td>");
									carIds += carsConfig[2]+",";
								}
								buf.append("</tr>");
								for(List<String> list: trList){
									if(list != null && list.size()>0){
										buf.append("<tr>");
										boolean isRed = "官方价".equals(list.get(0));
										for(int i = 0; i< list.size(); i++){
											if(i==0){
												buf.append("<td class=\"s-gray7\">"+list.get(i)+"</td>");
											}else {
												if(isRed){
													buf.append("<td class=\"s-red\">"+list.get(i)+"</td>");
												}else {
													if("●".equals(list.get(i)) || "○".equals(list.get(i)) || "-".equals(list.get(i))){
														buf.append("<td class=\"s-gray9\">"+list.get(i)+"</td>");
													}else {
														buf.append("<td>"+list.get(i)+"</td>");
													}
												}
											}
										}
										buf.append("</tr>");
									}
								}
								carIds = carIds.length()>0?carIds.substring(0, carIds.length()-1):"";
								buf.append("<tr><td colspan=\""+(carsList.size()+1)+"\"><a href=\"pcaction://serial-list-pk?carIds=["+carIds+"]\" class=\"btn-more s-blue\">查看全部参数<i class=\"u-arr u-arr-r\"></i></a></td></tr></tbody></table>");

							}else if (handleRet == 17) {//如果是全景图
								String s = html.substring(start, pos + tagEnd.length());
								buf.append(s);
							}else if (handleRet == 18) {//如果是自定义表格
								String s = html.substring(start, pos + tagEnd.length());
								Matcher colMatcher = Pattern.compile("colspan=\"(\\d*?)\"").matcher(s);
								String colspan = colMatcher.find()?colMatcher.group(1):"";
								String title = "";
								Matcher matcher = Pattern.compile("<tr.*?><td.*?colspan=\"(\\d*?)\".*?>(.*?)</td></tr>").matcher(s);
								if(matcher.find()){
									title = matcher.group(2).replaceAll("<.*?>", "").replaceAll("</.*?>", "");
								}
								Matcher trMatcher = Pattern.compile("<tr[^>]*?iscontent=\"1\">([\\s\\S]*?)</tr>").matcher(s);
								buf.append("<table class=\"m-table m-auto\"><tbody>");
								if(!"".equals(title)){
									buf.append("<tr><th colspan=\""+colspan+"\"><span class=\"th\">"+title+"</span></th></tr>");
								}
								while(trMatcher.find()){
									buf.append("<tr>");
									Matcher tdMatcher = Pattern.compile("<td.*?>(.*?)</td>").matcher(trMatcher.group(1));
									while (tdMatcher.find()) {
										Matcher colsM = Pattern.compile("colspan=\"(\\d*?)\"").matcher(tdMatcher.group(0));
										String colspanNum = (colsM.find()?"colspan=\""+colsM.group(1)+"\"":"");
										Matcher rowsM = Pattern.compile("rowspan=\"(\\d*?)\"").matcher(tdMatcher.group(0));
										String rowspanNum = (rowsM.find()?"rowspan=\""+rowsM.group(1)+"\"":"");
										buf.append("<td " + colspanNum + rowspanNum + " >");

										buf.append(tdMatcher.group(1).replaceAll("<a.*?>", "").replaceAll("</a.*?>", "")+"</td>");
									}
									buf.append("</tr>");
								}
								if(s.indexOf("数据来源")!=-1){
									buf.append("<tr><td colspan=\""+colspan+"\" class=\"m-subtxt s-gray9\"><span class=f-fl>注：数据来源</span><span class=\"f-fr\">制表：太平洋汽车网</span></td></tr>");
								}
								buf.append("</tbody></table>");
							}else if (handleRet == 19) {
								String s = html.substring(start, pos + tagEnd.length() + 6);
								pos =  pos + 6;
								String newStr = change4AiTable(s);
								buf.append(newStr);
							}
							else if (handleRet == 191) {
								String s = html.substring(start, pos + tagEnd.length());
								String newStr = change4AiTable(s);
								buf.append(newStr);
							}
							else if (handleRet == 20) {
								String s = html.substring(start, pos + tagEnd.length());
								String newCmt = change4AiCmt(s);
								buf.append(newCmt);
							} else if (handleRet == 21) {
								pos =  pos + 6;
							}
							return pos + tagEnd.length();
						} else {
							//
						}
					}
				}
			}
			return 0;
		} else {
			buf.append(html.substring(start, end));
			return 0;
		}
	}

	public static interface TagHandler {
		int handle(StringBuilder buf, Tag tag, boolean begin);
	}

	public static final TagHandler BLOCK_TAG_HANDLER = new TagHandler() {
		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			buf.append("<br/>");
			return 0;
		}
	};

	public static final TagHandler IMG_TAG_HANDLER = new TagHandler() {
		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			String w = tag.getAttr("width");
			if (w != null) {
				if (w.length() == 1 && (w.charAt(0) == '1' || w.charAt(0) == '0')) {
					// user ad
					return 0;
				}
			}
			if (! inTable.get()) {
				buf.append("<img");
				buf.append(" class=\"bigimg\" onclick=\"viewPic(this, event);\"");
			} else {
				buf.append("<IMG class=\"tabimg\"");
			}
			buf.append(" src=\"");
			if (! thumbImg.get() || inTable.get()) {
				buf.append(HtmlCMSUtils.filterWapImg(tag.getAttr("src"), 450));
			} else {
				buf.append(HtmlCMSUtils.filterWapImg(tag.getAttr("src"), 150));
			}
			buf.append("\" ");
			if("pconline".equalsIgnoreCase(getSiteName())||"pcauto".equalsIgnoreCase(getSiteName())){
				buf.append(" data-width=\"").append(StringUtils.defaultIfEmpty(tag.getAttr("data-width"),"0")).append("\"");
				buf.append(" data-height=\"").append(StringUtils.defaultIfEmpty(tag.getAttr("data-height"),"0")).append("\"");
			}
			buf.append("/>");
			return 0;
		}
	};

	public static final TagHandler A_TAG_HANDLER = new TagHandler() {
		private boolean allowAppend(String category) {
			return true;
		}

		private boolean allowAppend(String firstWord, String secondWord){
			if("pdlib".equals(firstWord) || "series".equals(secondWord)){
				return false;
			}else{
				return true;
			}
		}

		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			if (begin) {
				String href = tag.getAttr("href");
				//把双斜杠和https替换为http进行判断,因为总出口还是会替换回来的，这里便于维持之前的逻辑判断
				href = HtmlCMSUtils.replaceHttpUrl(href);

				if(!StringUtils.isBlank(href) && (href.startsWith("http://www1.pcauto.com.cn/piclib/")
						|| href.startsWith("http://www1.pcauto.com.cn/panorama/"))){//如果是全景图
					return 17;
				}

				if (!StringUtils.isBlank(href) && (
						href.startsWith("http://itunes.apple.com/") ||
								href.startsWith("https://itunes.apple.com/") ||
								href.endsWith(".apk") ||
								href.endsWith("&brower=inner") ||
								href.equals("javascript:void(888);") || //直播
								href.startsWith("./"))) {
					return 2;
				}

				if (!StringUtils.isBlank(href)) {
					href = href.trim();
					if (href.startsWith("http://product.pconline.com.cn")) {
						Pattern pattern = Pattern.compile("^http:\\/\\/product.pconline.com.cn\\/(\\w+)\\/(\\w+)\\/(\\d+)\\.html$");
						Matcher matcher = pattern.matcher(href);
						if(matcher.matches()){
							if(allowAppend(matcher.group(1),matcher.group(2))){
								buf.append( "<a  class='rlink' onclick='if(event)event.stopPropagation();' href='pconlinebrowser://product-detail/")
										.append(matcher.group(3)).append("'>");
								return 3;
							}
						}
					} else if (href.startsWith("http://itbbs.pconline.com.cn")) { //跳往电脑网论坛
						Pattern pattern = Pattern.compile("^http:\\/\\/itbbs.pconline.com.cn\\/(\\w+)\\/(\\d+)\\.html$");
						Matcher matcher = pattern.matcher(href);
						if (matcher.matches()) {
							if (allowAppend(matcher.group(1))) {
								buf.append("<a  class='rlink' onclick='if(event)event.stopPropagation();' href='pconlinebrowser://bbs-topic/").append(matcher.group(2)).append("'>");
								return 4;
							}
						}
					} else if (href.startsWith("http://bbs.pcauto.com.cn")) { //跳往汽车网论坛
						Pattern pattern = Pattern.compile("^http:\\/\\/bbs.pcauto.com.cn\\/(topic|forum)-(\\d+)\\.html$");
						Matcher matcher = pattern.matcher(href);
						if (matcher.matches()) {
							if ("topic".endsWith(matcher.group(1))&&!StringUtils.isBlank(matcher.group(2))) {
								buf.append("<a  class='rlink' onclick='if(event)event.stopPropagation();' href='pcautobrowser://bbs-topic/").append(matcher.group(2)).append("'>");
								return 4;
							}
							if ("forum".endsWith(matcher.group(1))&&!StringUtils.isBlank(matcher.group(2))) {
								buf.append("<a  class='rlink' onclick='if(event)event.stopPropagation();' href='pcautobrowser://bbs-topics/").append(matcher.group(2)).append("'>");
								return 4;
							}
						}
					} else if (href.startsWith("http://price.pcauto.com.cn")) {//跳往汽车报价库
						String browser = HtmlCMSUtils.getPcautoBrowser(href);
						if (!StringUtils.isBlank(browser)) {
							buf.append("<a  class='rlink' onclick='if(event)event.stopPropagation();' href='").append(browser).append("'>");
							return 3;
						}
					} else if (href.startsWith("pcladybrowser://album-photo/")) {//女性网图库
						return 2;
					} else if (href.startsWith("http://bbs.pcgames.com.cn")){
						return 0;
					} else if (href.startsWith("http://live.pcauto.com.cn")){
						Pattern pattern = Pattern.compile("^http:\\/\\/live.pcauto.com.cn\\/broadRecord.jsp\\?broadcastId=(\\S+)$");
						Matcher matcher = pattern.matcher(href);
						if(matcher.find()){
							buf.append("<a target=\"_blank\" href='pcaction://live-article/").append(matcher.group(1)).append("' >");
							return 4;
						}
					} else if (href.startsWith("http://pcauto.pcvideo.com.cn/video-")) {//视频视频链点
						String videoUrl = href.replaceAll("http://pcauto.pcvideo.com.cn/video-", "http://m.pcauto.pcvideo.com.cn/v_");
						buf.append("<a target=\"_blank\" href=\"").append(videoUrl).append("\" >");
					} else if (href.matches("http://live.pcvideo.com.cn/(live|playback)/.*?")) {
						String liveStr = href.replaceAll(".*?/(live|playback)/(.*?).html", "$1/$2");
						if (liveStr.startsWith("live/")) {
							liveStr = liveStr.replaceAll("live/", "play/");
						}
						buf.append("<a target=\"_blank\" href=\"").append("https://live.pcvideo.com.cn/m/" + liveStr + ".html").append("\" >");
					}
					else {//汽车网或电脑网的相关文章
						Pattern pcautoPattern = Pattern.compile("^http:\\/\\/(\\w+).(pcauto|pconline|pclady|pcbaby|pcgames).com.cn\\/.*?(\\d+)\\/(\\d+)(_\\d+|_all)?\\.html$");
						Matcher matcher = pcautoPattern.matcher(href);
						if(matcher.matches()){
							if("pcauto".equalsIgnoreCase(getSiteName())){
								String pageNo = matcher.group(5);
								int pageNum = 0;
								if(!StringUtils.isBlank(pageNo) && pageNo.matches("_\\d+")){
									pageNum = NumberUtils.toInt(pageNo.substring(1));
									pageNo = "?pageNo=" + (pageNum + 1);
								}else{
									pageNo = "?pageNo=1";
								}
								buf.append("<a  class='rlink' onclick='if(event)event.stopPropagation();' href='").append(matcher.group(2)).append("browser://information-article/")
										.append(matcher.group(4)).append(pageNo).append("'>");
							}else{
								buf.append("<a  class='rlink' onclick='if(event)event.stopPropagation();' href='").append(matcher.group(2)).append("browser://information-article/").append(matcher.group(4)).append("'>");
							}
							return 4;
						}else{
							if("pcgames".equalsIgnoreCase(getSiteName())){
								buf.append("<a target=\"_blank\" href=\"").append(href).append(href.indexOf("?") != -1 ? "&" : "?").append("browser=commonWebView\" >");
								return 6;
							}
							if("pconline".equals(getSiteName())){
								buf.append("<a target=\"_blank\" href=\"").append(href).append(href.indexOf("?") != -1 ? "&" : "?").append("browser=fullscreen\" >");
								return 6;
							}
						}
					}
				}
			}else{
				int leftSquareBracketPosition=buf.lastIndexOf("<a");
				int rightSquareBracketPosition=buf.lastIndexOf("</a");
				if(leftSquareBracketPosition>rightSquareBracketPosition ){
					buf.append('<').append('/').append(tag.getName()).append('>');
				}
			}
			return 0;
		}
	};

	//清空标签及标签体
	public static final TagHandler REMOVE_TAG_HANDLER = new TagHandler() {
		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			return 1;
		}
	};

	//清空标签但保留标签体（针对占位标签）
	public static final TagHandler EMPTY_TAG_HANDLER = new TagHandler() {
		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			return 0;
		}
	};

	public static final TagHandler KEEP_TAG_HANDLER = new TagHandler() {
		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			if (begin) {

				String div_class = tag.getAttr("class");
				if(div_class != null && "softjs2".equals(div_class)){
					return 10;
				}
				if(div_class != null && "softjs3".equals(div_class)){
					return 11;
				}
				//如果有图片描述转换标识，进行结构转换
				String describepicture = tag.getAttr("describepicture");
				if (StringUtils.isNotBlank(describepicture)) {
					return 12;
				}

				//180417 新版 软件下载代码块过滤
				if ("dl".equals(tag.getName()) && "softjs4".equals(tag.getAttr("class"))) {
					//直接过滤掉
					return 1;
				}

				List<String> attrs=tag.getAttrs();
				buf.append('<').append(tag.getName());
				for (String attr : attrs) {
					String a = tag.getAttr(attr);
					if("width".equalsIgnoreCase(attr) && !"iframe".equalsIgnoreCase(tag.getName())) continue;
					if (a != null){
						buf.append(' ').append(attr).append('=').append('"').append(a).append('"');
					}
				}
				buf.append('>');
			} else {
				buf.append('<').append('/').append(tag.getName()).append('>');
			}
			return 0;
		}
	};

	public static final TagHandler FORM_TAG_HANDLER = new TagHandler() {
		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {

			return 5;
		}
	};

	public static final TagHandler KEEP_IN_TABLE_TAG_HANDLER = new TagHandler() {
		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			if (inTable.get()) {
				if (begin) {
					buf.append('<').append(tag.getName()).append('>');
				} else {
					buf.append('<').append('/').append(tag.getName()).append('>');
				}
			} else {
				buf.append("<br/>");
			}
			return 0;
		}
	};


	public static final TagHandler TD_TAG_HANDLER = new TagHandler() {
		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			if (begin) {
				buf.append('<').append(tag.getName());
				boolean isBgDark = trBgColorDark.get();
				List<String> attrs=tag.getAttrs();
				for (String attr : attrs) {
					if("width".equalsIgnoreCase(attr)) continue;
					String a = tag.getAttr(attr);
					if (a != null){
						buf.append(' ').append(attr).append('=').append('"').append(a).append('"');
						if ("bgcolor".equals(attr)) {
							isBgDark = isColorDark(a);
						}
					}
				}
				if (isBgDark) {
					buf.append(" class=\"theader\"");
				}
				buf.append('>');
			} else {
				buf.append('<').append('/').append(tag.getName()).append('>');
			}
			return 0;
		}
	};

	public static final TagHandler DIV_LIVE_HANDLER = new TagHandler() {
		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			if (begin) {
				String div_class = tag.getAttr("class");
				if (div_class!= null){
					if(div_class.equals("dLive")||
							div_class.startsWith("dBtn")||
							div_class.equals("dMain")||
							div_class.equals("dBox")||
							div_class.equals("block")||
							div_class.equals("dTh")
					){
						inLive.set(true);
					}
					if(inLive.get()){
						if(div_class.equals("block")){
							buf.append('<').append(tag.getName());
							buf.append(' ').append("class").append('=').append('"').append(div_class).append('"');
							buf.append('>');
						}else{
							return 2;
						}
					}
				}
			} else {
				if(inLive.get()){
					buf.append('<').append('/').append(tag.getName()).append('>');
				}else{
					buf.append("<br/>");
				}
				inLive.set(false);
			}
			return 0;
		}
	};

	public static final TagHandler TABLE_TAG_HANDLER = new TagHandler() {
		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			if (begin) {
				//如果有isCarParameter标志，替换车型参数表格
				String isCarparameter = tag.getAttr("iscarparameter");
				if (StringUtils.isNotBlank(isCarparameter)) {
					return 9;
				}
				//如果有图片表格标志，进行结构替换
				String isPicTab = tag.getAttr("ispictab");
				if (StringUtils.isNotBlank(isPicTab)) {
					//180601 新版转换
					if ("2".equals(isPicTab)) {
						return 131;
					}
					return 13;
				}
				//如果有图片描述转换标识，进行结构转换
				String describepicture = tag.getAttr("describepicture");
				if (StringUtils.isNotBlank(describepicture)) {
					return 12;
				}
				//如果有iswap标志，需要替换车型报价模块结构，返回return 3
				String isWap = tag.getAttr("iswap");
				if (StringUtils.isNotBlank(isWap)) {
					return 15;
				}
				String isselfdefine = tag.getAttr("isselfdefine");
				//如果自定义表格，进行结构转换
				if (StringUtils.isNotBlank(isselfdefine)) {
					return 18;
				}
				//如果是点评表格，进行结构转换
				String classValue = tag.getAttr("class");
				if (StringUtils.isNotBlank(classValue) && (classValue.equals("evaluationTable port tabB10")
						|| classValue.equals("evaluationTable evaluationTableA port tabB10"))) {
					return 14;
				}
				//如果有可选分类车系参配标识，进行结构转换
				if (StringUtils.isNotBlank(classValue) && (classValue.equals("configTable port tabB10")
						|| classValue.equals("configTable configTableA port tabB10"))) {
					return 16;
				}

				inTable.set(true);
				buf.append('<').append(tag.getName());
				List<String> attrs=tag.getAttrs();
				for (String attr : attrs) {
					if("width".equalsIgnoreCase(attr)) continue;
					String a = tag.getAttr(attr);
					if (a != null){
						buf.append(' ').append(attr).append('=').append('"').append(a).append('"');
					}
				}
				buf.append('>');
			} else {
				buf.append('<').append('/').append(tag.getName()).append('>');
				inTable.set(false);
			}
			return 0;
		}
	};

	public String change4PicTable(String picTable) {
		StringBuilder wapPicTable = new StringBuilder();
		String carNameRegx = "(?i)<dt\\s*class=\"artPriPortCar\"\\ssgid=\"(.*?)\"\\ssgpic=\"(.*?)\"><strong><a\\shref=\"(.*?)\".*?>(.*?)</a></strong></dt>";
		Pattern carNamePat = Pattern.compile(carNameRegx);
		Matcher carNameMat = carNamePat.matcher(picTable);
		//车系名称
		List<String> carNames = new ArrayList<String>();
		//车系图片
		List<String> carPics = new ArrayList<String>();
		//车系图片
		List<String> carIds = new ArrayList<String>();
		List<String> carUrls = new ArrayList<String>();
		while (carNameMat.find()) {
			String carName = carNameMat.group(4) != null ? carNameMat.group(4) : "";
			carNames.add(carName);
			String carPic = carNameMat.group(2) != null ? carNameMat.group(2) : "";
			carPics.add(carPic);
			String carId = carNameMat.group(1) != null ? carNameMat.group(1) : "";
			carIds.add(carId.trim());
			String carUrl = carNameMat.group(3) != null ? carNameMat.group(3) : "";
			carUrls.add(carUrl.trim());
		}
		//询底价链点
		String orderRegx = "(?i)<td\\sclass=\"artpriPortColC\"><a class=\"artpriPortAsk\"\\s*href=\"(.*?)\".*?>";
		Pattern orderPat = Pattern.compile(orderRegx);
		Matcher orderMat = orderPat.matcher(picTable);
		List<String> orderUrls = new ArrayList<String>();
		while (orderMat.find()) {
			String orderUrl = orderMat.group(1) != null ? orderMat.group(1) : "";
			orderUrls.add(HtmlCMSUtils.getPcautoBrowser(orderUrl));
		}
		//价格范围
		String prieRexg = "(?i)<p\\sclass=\"artpriPortPriceA\">.*?<a.*?>(.*?)</a></p>";
		Pattern priePat = Pattern.compile(prieRexg);
		Matcher prieMat = priePat.matcher(picTable);
		List<String> prieRanges = new ArrayList<String>();
		while (prieMat.find()) {
			String prieRange = prieMat.group(1) != null ? prieMat.group(1) : "";
			prieRanges.add(prieRange);
		}
		try {
			if (!carNames.isEmpty()) {
				//组装新结构
				wapPicTable.append("<ul class=\"m-list m-carlist\">");
				for (int i = 0; i < carNames.size(); i++) {
					//170801 app协议要求必传车系和车系名
					String carUrl = carUrls.get(i);
					//PWD
					carUrl = HtmlCMSUtils.getPcautoBrowser(carUrl);
					wapPicTable.append("<li>")
							.append("<a onclick='if(event)event.stopPropagation();' href='"+carUrl+"'>")
							.append("<p class=\"pic f-fl\"><IMG src=\"").append(HtmlCMSUtils.replaceHttpUrl(carPics.get(i))).append("\" alt=\"\" class=\"pic-xdj\" ></p>")
							.append("<p class=\"txt f-fl\">")
							.append("<span>"+carNames.get(i)+"</span>")
							.append("<em><i class=\"s-gray9\">官方价：</i><i class=\"s-red\">"+prieRanges.get(i)+"</i></em>")
							.append("</p>")
							.append("</a>")
							.append("<a href=\""+orderUrls.get(i)+"\" class=\"btn-xdj f-fr s-blue\">获取底价</a>")
							.append("</li>");
				}
				wapPicTable.append("</ul>");
			}
		} catch(Exception e) {
			System.out.println("app 转换表格图片出错");
			e.printStackTrace();
		}
		return wapPicTable.toString();
	}

	public String change4PicTable2(String picTable) {
		StringBuilder wapPicTable = new StringBuilder();
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();

		String[] trs = picTable.split("</tr>");
		if (trs != null && trs.length > 1) {
			for (int i = 0; i < trs.length - 1; i++) {
				String tr = trs[i];
				String sgName = null, mName = null, sgPic = null, sgId = null, mId = null, prieRange = null, sale = null, mpr = null;
				if (tr.matches(".*\\ssgid=\"([^\"]+)\".*")) {
					sgId = tr.replaceAll(".*\\ssgid=\"([^\"]+)\".*", "$1");
				}
				if (tr.matches(".*\\ssgpic=\"([^\"]+)\".*")) {
					sgPic = tr.replaceAll(".*\\ssgpic=\"([^\"]+)\".*", "$1");
				}
				if (tr.matches(".*\\smid=\"([^\"]+)\".*")) {
					mId = tr.replaceAll(".*\\smid=\"([^\"]+)\".*", "$1");
				}
				if (tr.matches(".*\\ssgname=\"([^\"]+)\".*")) {
					sgName = tr.replaceAll(".*\\ssgname=\"([^\"]+)\".*", "$1");
				}
				if (mId != null && tr.matches(".*\\stitle=\"([^\"]+)\".*")) {
					mName = tr.replaceAll(".*\\stitle=\"([^\"]+)\".*", "$1");
				}
				if (tr.matches(".*\\ssale=\"([^\"]+)\".*")) {
					sale = tr.replaceAll(".*\\ssale=\"([^\"]+)\".*", "$1");
				}
				if (tr.matches(".*\\sprierange=\"([^\"]+)\".*")) {
					prieRange = tr.replaceAll(".*\\sprierange=\"([^\"]+)\".*", "$1");
				}
				if (tr.matches(".*\\smpr=\"([^\"]+)\".*")) {
					mpr = tr.replaceAll(".*\\smpr=\"([^\"]+)\".*", "$1");
				}
				Map<String, String> map = new HashMap<String, String>();
				map.put("sgId", sgId);
				map.put("sgName", sgName);
				map.put("sgPic", sgPic);
				map.put("mId", mId);
				map.put("mName", mName);
				map.put("sale", sale);
				map.put("prieRange", prieRange);
				map.put("mpr", mpr);
				list.add(map);
			}
		}
		String template = "<li>"
				+"<a onclick=\"if(event)event.stopPropagation();\" href=\"{url_car}\">"
				+"<p class=\"txt f-fl txt-width\">"
				+"<span class=\"car-tit\">{carName}</span>"
				+"{sale}<span class=\"more-pre\">查看更多优惠&gt;</span>{sale}"
				+"<em>"
				+"<i class=\"s-gray9 s-gray9-one\">{sale}商家报价{sale}{noSale}预售价{noSale}:</i>"
				+"<i class=\"s-red\">{prieRange}</i>"
				+"</em>"
				+"{sale}<span class=\"downPri green\">{mpr}</span>{sale}"
				+"</p>"
				+"</a>"
				+"{sale}<a href=\"{url_fenqi}\" class=\"btn-xdj f-fr s-blue btn-xdj-one s-0777dd\">分期购车</a>{sale}"
				+"<a href=\"{url_dijia}\" class=\"btn-xdj f-fr s-blue btn-xdj-one\">获取底价</a>"
				+"</li>";
		try {
			if (!list.isEmpty()) {
				//组装新结构
				wapPicTable.append("<ul class=\"m-list m-carlist\">");
				for (Map<String, String> map : list) {
					//170801 app协议要求必传车系和车系名
					boolean isModel = map.get("mId") != null;
					boolean isSale = !"0".equals(map.get("sale"));
					String carName = map.get("sgName");
					String url_car = "pcautobrowser://";
					if (isModel) {
						url_car += "model/"+map.get("mId")+"?serialId="+map.get("sgId")+"&serialName=" + map.get("sgName");
						carName = map.get("mName");
					} else {
						url_car += "serial/"+map.get("sgId");
					}
					//分期购车链接
					String url_fenqi = "pcautobrowser://modelPayment/?url=https://m-jr.pcauto.com.cn/planInfo/r1/sg" + map.get("sgId");
					if (isModel) {
						url_fenqi += "-m" + map.get("mId");
					}
					url_fenqi += "/";
					//获取低价
					String url_dijia = "pcautobrowser://auto-ask-price/?";
					if (isModel) {
						url_dijia += "modelId="+map.get("mId")+"&serialId="+map.get("sgId")+"&modelName="+map.get("mName")+"&dealerId=&dealerName=&image="+map.get("sgPic");
					} else {
						url_dijia += "serialId="+map.get("sgId")+"&modelName=&dealerId=&dealerName=&image=";
					}
					String html_li = null;
					if (isSale) {
						html_li = template.replaceAll("\\{sale\\}", "")
								.replaceAll("\\{noSale\\}.*?\\{noSale\\}", "");
					} else {
						html_li = template.replaceAll("\\{noSale\\}", "")
								.replaceAll("\\{sale\\}.*?\\{sale\\}", "");
					}
					html_li = html_li.replace("{url_dijia}", url_dijia)
							.replace("{carName}", carName)
							.replace("{url_fenqi}", url_fenqi)
							.replace("{prieRange}", map.get("prieRange"))
							.replace("{url_car}", url_car);
					if (map.get("mpr") != null) {
						html_li = html_li.replace("{mpr}", "最高降"+map.get("mpr")+"万");
					} else {
						html_li = html_li.replace("{mpr}", "");
					}
					wapPicTable.append(html_li);
				}
				wapPicTable.append("</ul>");
			}
		} catch(Exception e) {
			System.out.println("app 转换表格图片出错");
			e.printStackTrace();
		}
		return wapPicTable.toString();
	}

	public String change4hqTable(Tag tag, String hqTable) {
		//根据原来结构截取tr内容出来,先把之前的行情标题信息截取出来
		List<String> trList = new ArrayList<String>();
		String trRegx = "(?i)<tr[^>]*?>([\\s\\S]*?)</tr[^>]*?>";
		Pattern pattern = Pattern.compile(trRegx);
		Matcher trMatch = pattern.matcher(hqTable);
		while (trMatch.find()){
			trList.add(trMatch.group(1));
		}
		//获取第一个tr内容得到车系名称和对应链点,并且拼接图片、配置、点评链点
		String carName = "";
		String carUrl = "";
		String priTableTit = "";
		if (trList.size() > 0) {
			priTableTit = trList.get(0);
		}
		if (StringUtils.isNotBlank(priTableTit)) {
			List<Map<String, String>> titList = getDataByATag(priTableTit);
			if (titList != null && titList.size() > 0) {
				Map<String, String> titMap = titList.get(0);
				carName = titMap.get("aName") != null ? titMap.get("aName") : "";
				carUrl = titMap.get("aUrl") != null ? titMap.get("aUrl") : "";
				carUrl = HtmlCMSUtils.getPcautoBrowser(carUrl);
			}
		}

		//获取其他tr的型号、价格等数据并封装
		List<Map<String, String>> prieList = new ArrayList<Map<String, String>>();
		for (int i = 1; i < trList.size() - 1; i++) {
			String dataTr = trList.get(i);
			Map<String, String> prieMap = new HashMap<String, String>();
			List<Map<String, String>> dataList = getDataByATag(dataTr);
			if (dataList != null && dataList.size() > 0) {
				//型号名称和链点
				Map<String, String> carMap = dataList.get(0);
				//型号名称
				prieMap.put("carModel", carMap.get("aName") != null ? carMap.get("aName") : "");
				//型号链点
				String carModelUrl = carMap.get("aUrl") != null ? carMap.get("aUrl") : "";
				String carModelUrlWap = HtmlCMSUtils.getPcautoBrowser(carModelUrl);
				prieMap.put("carModelUrl", carModelUrlWap);
				//询底价链点
				String carLowUrl = "";
				if (dataList.size() >= 2) {
					Map<String, String> urlMap = dataList.get(1);
					carLowUrl =  urlMap.get("aUrl") != null ? urlMap.get("aUrl") : "";
					prieMap.put("carLowUrl", HtmlCMSUtils.getPcautoBrowser(carLowUrl));
				}
			}
			//型号官方价
			prieMap.put("carGovPrie", getDataByPTag(dataTr, "priTableColB"));
			//型号优惠价
			prieMap.put("carFavPrie", getDataByPTag(dataTr, "priTableColC").replaceAll("<i>(.*?)</i>", "$1"));
			//型号现价
			prieMap.put("carNowPrie", getDataByPTag(dataTr, "priTableColD"));
			prieList.add(prieMap);
		}
		//拼接wap版新行情表格结构
		StringBuilder wapHqTable = new StringBuilder();
		wapHqTable.append("<table class=\"m-table m-price\"><tbody>")
				.append("<tr><th class=\"line1\">"+carName+"</th><th class=\"line2\">官方价</th><th class=\"line3\">优惠幅度</th><th class=\"line4\">现价</th><th class=\"line5\">获取底价</th></tr>");
		//车型价格拼接
		for (Map<String, String> prieMap : prieList) {
			wapHqTable.append("<tr>")
					.append("<td class=\"line1\"><a href=\""+prieMap.get("carModelUrl")+"\" class=\"s-blue\">"+prieMap.get("carModel")+"</a></td>")
					.append("<td class=\"line2\">"+prieMap.get("carGovPrie")+"</td>")
					.append("<td class=\"line3 s-green\">"+prieMap.get("carFavPrie")+"</td>")
					.append("<td class=\"line4 s-red\">"+prieMap.get("carNowPrie")+"</td>");
			String tdContent = "--";
			if (prieMap.get("carLowUrl")!=null && !"".equals(prieMap.get("carLowUrl"))){
				tdContent = "<a href=\""+prieMap.get("carLowUrl")+"\" class=\"btn-xdj\">获取底价</a>";
			}
			wapHqTable.append("<td class=\"line5\">"+tdContent+"</td>")
					.append("</tr>");
		}
		wapHqTable.append("</tbody></table>");
		return wapHqTable.toString();
	}

	//根据A标签获取href链点以及名称，替换行情表格使用
	public  List<Map<String, String>> getDataByATag(String content) {
		List<Map<String, String>> dataList = new ArrayList<Map<String, String>>();
		String aTagRegx = "(?i)<a[\\s\\S]*? href\\s*=\\s*[\"']([\\s\\S]*?)[\"'][\\s\\S]*?>([\\s\\S]*?)</a\\s*>";
		Pattern aTagPat = Pattern.compile(aTagRegx);
		Matcher aTagMatch  = aTagPat.matcher(content);
		while (aTagMatch.find()) {
			Map<String, String> dataMap = new HashMap<String, String>();
			dataMap.put("aName", aTagMatch.group(2));
			dataMap.put("aUrl", aTagMatch.group(1));
			dataList.add(dataMap);
		}
		return dataList;
	}

	//根据P标签和对应的class属性或者内容，替换行情表格使用
	public String getDataByPTag(String content, String className) {
		String dataStr = "";
		String pTagRegx = "(?i)<p\\s* class\\s*=\\s*[\"']" + className + "[\"'][\\s\\S]*?>([\\s\\S]*?)</p\\s*>";
		Pattern pTagPat = Pattern.compile(pTagRegx);
		Matcher pTagMatch = pTagPat.matcher(content);
		if (pTagMatch.find()) {
			dataStr = pTagMatch.group(1);
		}
		return dataStr;
	}

	public static final TagHandler TR_TAG_HANDLER = new TagHandler() {
		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			if (begin) {
				buf.append('<').append(tag.getName());
				List<String> attrs=tag.getAttrs();
				for (String attr : attrs) {
					if("width".equalsIgnoreCase(attr)) continue;
					String a = tag.getAttr(attr);
					if (a != null){
						if ("bgcolor".equals(attr)) {
							trBgColorDark.set(isColorDark(a));
						}
						buf.append(' ').append(attr).append('=').append('"').append(a).append('"');
					}
				}
				buf.append('>');
			} else {
				buf.append('<').append('/').append(tag.getName()).append('>');
				trBgColorDark.set(false);
			}
			return 0;
		}
	};

	public static final TagHandler EMBED_TAG_HANDLER = new TagHandler() {
		String special = "flashvars";
		boolean isMatch = false;
		String src = null;

		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			String flv = null;
			String thumb = null;

			String fs = tag.getAttr(special);
			if(fs != null) {
				Pattern p1 = Pattern.compile("flv=((http://(flv|online|auto|baby|lady|house|gflv).pcvideo.com.cn/)?(pcgames|pconline|pclady|pcauto|pchouse|pcbaby)\\/.+\\.mp4)");
				Matcher m1 = p1.matcher(fs);
				if(m1.find()) {
					flv = m1.group(1);
					if(flv.indexOf("http://") == -1) {
						flv = "http://flv.pcvideo.com.cn/" + flv;
					}
				}

				Pattern p2 = Pattern.compile("thumb=((http://)?.*?.(pcgames|pconline|pclady|pcauto|pchouse|pcbaby|pcvideo)(.com.cn)\\/.+\\.jpg)");
				Matcher m2 = p2.matcher(fs);
				if(m2.find()) {
					thumb = m2.group(1);
					if(thumb.indexOf("http://") == -1) {
						thumb = "http://flv.pcvideo.com.cn/" + thumb;
					}
				}
			}

			if(begin){
				if (flv != null ) {//站内视频
					buf.append("<div class=\"section1-a\">");
					buf.append('<').append("video");
					buf.append(' ').append("width").append('=').append('"').append("300").append('"');
					buf.append(' ').append("height").append('=').append('"').append("225").append('"');

					buf.append(' ').append("controls").append('=').append('"').append("controls").append('"');
					buf.append(' ').append("preload").append('=').append('"').append("none").append('"');

					if(thumb != null) {
						buf.append(' ').append("poster").append('=').append('"').append(thumb).append('"');
					}

					buf.append('>');

					buf.append("<source type=\"video/mp4\" src=\"");
					buf.append(flv);
					buf.append("\" />");

					buf.append("<source type=\"video/webm\" src=\"");
					buf.append(flv);
					buf.append("\" />");

					buf.append("<source type=\"video/ogg\" src=\"");
					buf.append(flv);
					buf.append("\" />");

					isMatch = true;
					src = flv;
				}
			} else {
				if(isMatch) {
					buf.append('<').append('/').append("video").append('>');
					buf.append("<a class=\"vText\" href=\"");
					buf.append(src);
					buf.append("\">点击播放</a></div>");
					isMatch = false;
					src = null;
				}
			}

			return 0;
		}
	};

	public static final TagHandler SCRIPT_TAG_HANDLER = new TagHandler() {
		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			if (begin) {
				String srcUrl = tag.getAttr("src");
				if(!StringUtils.isBlank(srcUrl))
					srcUrl = srcUrl.replace("dealer_list_show_js2.jsp", "dealer_list_show_js3.jsp");
//            	 String priceRoot = service.getConfigValue("autoprice_root_url", "");
				String priceRoot="price.pcauto.com.cn";
				if(!StringUtils.isBlank(srcUrl)&& (srcUrl.indexOf(priceRoot)!=-1)){
					inScript.set(true);
					List<String> attrs=tag.getAttrs();
					buf.append('<').append(tag.getName());
					for (String attr : attrs) {
						String a = tag.getAttr(attr);
						if("width".equalsIgnoreCase(attr)||"src".equalsIgnoreCase(attr)) continue;
						if (a != null){
							buf.append(' ').append(attr).append('=').append('"').append(a).append('"');
						}
					}
					srcUrl+=(srcUrl.indexOf("?")==-1?"?":"&")+"version_source=phone_client";
					if (srcUrl.indexOf("source")!=-1){
						srcUrl=srcUrl.replaceAll("source=0","source=2");
						buf.append(' ').append("src").append('=').append('"').append(srcUrl).append('"').append(' ').append("defer");
					}else {
						buf.append(' ').append("src").append('=').append('"').append(srcUrl).append('"').append(' ');
					}
					buf.append('>');
					return 0;
				}else{
					return 1;
				}
			} else {
				if(inScript.get()){
					buf.append('<').append('/').append(tag.getName()).append('>');
					inScript.set(false);
					return 0;
				}else{
					return 1;
				}
			}
		}
	};

	public static final TagHandler IFRAME_TAG_HANDLER = new TagHandler() {
		boolean isMatchYouku = false;
		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			if (begin) {
				String srcUrl = StringUtils.defaultIfEmpty(tag.getAttr("src"),"");
				srcUrl = HtmlCMSUtils.replaceHttpUrl(srcUrl);
				if(srcUrl.startsWith("http://www.pconline.com.cn/youku/iframe.html")){//替换优酷视频的iframe结构
					isMatchYouku = true;
					String youkuCode = "";
					int splitIndex = srcUrl.indexOf("#");
					if(splitIndex > 0 && srcUrl.length() > splitIndex + 1){
						youkuCode = srcUrl.substring(splitIndex + 1);
					}
					buf.append("<div id='youkuplayer"+  youkuCode + "'></div>");
				}else{
					isMatchYouku = false;
					boolean hasClass = false;
					List<String> attrs = tag.getAttrs();
					buf.append('<').append(tag.getName());
					for (String attr : attrs) {
						String a = tag.getAttr(attr);
						if("height".equalsIgnoreCase(attr)||"width".equalsIgnoreCase(attr)||"src".equalsIgnoreCase(attr)) continue;
						if (!StringUtils.isBlank(a)){
							if("class".equalsIgnoreCase(attr)){
								if(srcUrl.startsWith("http://music.163.com")){//添加class属性区分音频和视频,目前音频只有网易音乐使用iframe
									a = a + " u-iframe-audio";
								}else{
									a = a + " u-iframe-video";
								}
								hasClass = true;
							}
							buf.append(' ').append(attr).append('=').append('"').append(a).append('"');
						}
					}
					if(!hasClass){
						if(srcUrl.startsWith("http://music.163.com")){//添加class属性区分音频和视频,目前音频只有网易音乐使用iframe
							buf.append(' ').append("class").append('=').append('"').append("u-iframe-audio").append('"');
						}else{
							buf.append(' ').append("class").append('=').append('"').append("u-iframe-video").append('"');
						}
					}
					if(srcUrl.startsWith("http://yuntv.letv.com/bcloud.html")){
						if(srcUrl.indexOf("width=")!=-1)
							srcUrl=srcUrl.replaceAll("width=([^&]*)(&)?", "width=300$2");
						if(srcUrl.indexOf("height=")!=-1)
							srcUrl=srcUrl.replaceAll("height=([^&]*)(&)?", "height=225$2");
					} else {
						//170919 height按375的宽度等比例缩放
						try {
							int width = Integer.parseInt(tag.getAttr("width"));
							int height = Integer.parseInt(tag.getAttr("height"));
							height = height * 375 / width;
							buf.append(" width=\"100%\" height=").append('"').append(height).append('"');
						} catch (Exception e) {
						}
					}
					buf.append(' ').append("src").append('=').append('"').append(srcUrl).append('"');
					buf.append('>');
				}
			} else {
				if(!isMatchYouku){
					buf.append('<').append('/').append(tag.getName()).append('>');
				}
			}
			return 0;
		}
	};

	//嵌入音频播放器的object标签,目前遇到object标签结构的只转化成mp3
	public static final TagHandler OBJECT_TAG_HANDLER = new TagHandler() {

		@Override
		public int handle(StringBuilder buf, Tag tag, boolean begin) {
			if (begin) {
				return 7;
			}
			return 0;
		}
	};

	//替换图片表格
	public String change4Pic(String picString) {
		StringBuilder wapPicTable = new StringBuilder();
		String picRegx = "(?i)<a\\s*href=\"(.*?)\".*?><img\\s*alt=\"(.*?)\".*?src=\"(.*?)\".*?/></a>";
		Pattern picPat = Pattern.compile(picRegx);
		Matcher picMat = picPat.matcher(picString);
		String url = "";//暂时没用
		String alt = "";
		String picUrl = "";
		String desc = "";
		if (picMat.find()) {
			url = picMat.group(1) != null ? picMat.group(1) : "";
			alt = picMat.group(2) != null ? picMat.group(2) : "";
			picUrl = picMat.group(3) != null ? picMat.group(3) : "";
		}
		Matcher descMatcher = Pattern.compile("<span\\s.*?><i\\s.*?</i>(.*?)</span>").matcher(picString);
		desc = descMatcher.find()?descMatcher.group(1):"";
		if (StringUtils.isNotBlank(picUrl)) {
//	    	<div class="block">
//                <div style="position: relative; width: 100%; margin: 0 auto;">
//                    <img class="bigimg" src="http://www1.pcauto.com.cn/wap/2013/cms/img/loading.png" src2="http://imgw.pconline.com.cn/images/pcautogallery/modle/article/20168/12/spcgroup/width_800-qua_30/14709809494007400.jpg" onclick="getAllImg('http://imgw.pconline.com.cn/images/pcautogallery/modle/article/20168/12/spcgroup/width_800-qua_30/14709809494007400.jpg'); if(event) event.stopPropagation();"/>
//                </div>
//                <div class="m-des">前麦弗逊式独立悬架和后多连杆式独立悬架在舒适性上不输给同级别的竞争对手，通过性不错自然也收获了不少赞誉。</div>
//            </div>
			//mrobot要求图片都加上http协议
			picUrl = HtmlCMSUtils.replaceHttpUrl(picUrl);
			wapPicTable
					.append("<div class=\"block\">")
					.append("<div style=\"position: relative; width: 100%; margin: 0 auto;\">")
//	    	.append("<img class=\"bigimg\" src=\""+picUrl+"\" onclick=\"getAllImg('"+picUrl+"'); if(event) event.stopPropagation();\"/>")
					.append("<img class=\"bigimg\" onclick=\"viewPic(this, event);\" src=\""+picUrl+"\" />")
					.append("</div>");
			if(!"".equals(desc)){
				desc = desc.replaceAll("<a[^>]*?>", "").replaceAll("</a>", "");
				wapPicTable.append("<div class=\"m-des\">"+desc+"</div>");
			}
			wapPicTable.append("</div>");
		}
		return wapPicTable.toString();
	}

	//替换图片表格 180601 新
	public String change4Pic2(String picString) {
		StringBuilder wapPicTable = new StringBuilder();
		String picRegx = "(?i)<a\\s*href=\"(.*?)\".*?><img\\s*alt=\"(.*?)\".*?src=\"(.*?)\".*?/></a>";
		Pattern picPat = Pattern.compile(picRegx);
		Matcher picMat = picPat.matcher(picString);
		String url = "";//暂时没用
		String alt = "";
		String picUrl = "";
		String desc = "";
		if (picMat.find()) {
			url = picMat.group(1) != null ? picMat.group(1) : "";
			alt = picMat.group(2) != null ? picMat.group(2) : "";
			picUrl = picMat.group(3) != null ? picMat.group(3) : "";
		}
		Matcher descMatcher = Pattern.compile("<span\\s.*?><i\\s.*?</i>(.*?)</span>").matcher(picString);
		desc = descMatcher.find()?descMatcher.group(1):"";
		if (StringUtils.isNotBlank(picUrl)) {
			//mrobot要求图片都加上http协议
			picUrl = HtmlCMSUtils.replaceHttpUrl(picUrl);
			wapPicTable
					.append("<div class=\"block\">")
					.append("<div style=\"position: relative; width: 100%; margin: 0 auto;\">")
					.append("<div class=\"artPic\">")
					.append("<div id=\"img_11\" style=\"position: relative; width: 100%; margin: 0 auto;\">")
					/*.append("<img class=\"bigimg\" src=\"//w1ssl.pcauto.com.cn/wap/2013/cms/img/blank.png\" data-width=\"0\" data-height=\"0\" src2=\""+picUrl+"\" onclick=\"getAllImg('"+picUrl+"'); if(event) event.stopPropagation();\"/>")*/
					.append("<img class=\"bigimg\" onclick=\"viewPic(this, event);\" src=\""+picUrl+"\" />")
					.append("</div></div></div>");
			if(!"".equals(desc)){
				desc = desc.replaceAll("<a[^>]*?>", "").replaceAll("</a>", "");
				wapPicTable.append("<div class=\"m-des\">"+desc+"</div>");
			}
			wapPicTable.append("</div>");
		}
		return wapPicTable.toString();
	}

	public String change4AiTable(String aiTable) {
		StringBuilder newAiTable = new StringBuilder();
		if (!StringUtils.isBlank(aiTable)) {
			//拿隐藏的信息出来
			String infoRegx = "(?i)<div class=\"artMarketBox(.*)?\">\\s*(<div[\\s\\S]*?class=\"artMarketCon\"[\\s\\S]*?>)";
			Pattern infoPat = Pattern.compile(infoRegx);
			Matcher infoMat = infoPat.matcher(aiTable);
			String  artMutClass = "";
			String divInfo = "";
			if (infoMat.find()) {
				artMutClass = infoMat.group(1);
				divInfo = infoMat.group(2);
			}
			String agent = "";
			String dealname = "";
			String dealerid = "";
			String salesarea = "";
			String areaname = "";
			String sgId = "";
			if (!StringUtils.isBlank(divInfo)) {
				if (divInfo.matches("(?i).*\\sagent=\"([^\"]+)\".*")) {
					agent = divInfo.replaceAll(".*\\sagent=\"([^\"]+)\".*", "$1");
				}
				if (divInfo.matches("(?i).*\\sdealname=\"([^\"]+)\".*")) {
					dealname = divInfo.replaceAll(".*\\sdealname=\"([^\"]+)\".*", "$1");
				}
				if (divInfo.matches("(?i).*\\sdealerid=\"([^\"]+)\".*")) {
					dealerid = divInfo.replaceAll(".*\\sdealerid=\"([^\"]+)\".*", "$1");
				}
				if (divInfo.matches("(?i).*\\ssalesarea=\"([^\"]+)\".*")) {
					salesarea = divInfo.replaceAll(".*\\ssalesarea=\"([^\"]+)\".*", "$1");
				}
				if (divInfo.matches("(?i).*\\sareaname=\"([^\"]+)\".*")) {
					areaname = divInfo.replaceAll(".*\\sareaname=\"([^\"]+)\".*", "$1");
				}
				if (divInfo.matches("(?i).*\\ssgid=\"([^\"]+)\".*")) {
					sgId = divInfo.replaceAll(".*\\ssgid=\"([^\"]+)\".*", "$1");
				}
			}
			//获取具体的报价内容
			String priceRegx = "(?i)<tr>\\s*<td class=\"aCol1\">\\s*<a href=\"//price.pcauto.com.cn/m(.*?)/\" target=\"_blank\">(.*?)</a></td>"
					+ "\\s*<td class=\"aCol2\">(.*?)</td>"
					+ "\\s*<td class=\"aCol3(-1)?\">(.*?)</td>\\s*<td class=\"aCol4\">(.*?)</td>";
			Pattern pricePat = Pattern.compile(priceRegx);
			Matcher priceMat = pricePat.matcher(aiTable);
			List<Map<String, String>>  priceList = new ArrayList<Map<String, String>> ();
			while (priceMat.find()) {
				Map<String, String> priceMap = new HashMap<String, String>();
				String mid = priceMat.group(1);
				String mName = priceMat.group(2);
				String price = priceMat.group(3);
				String isaCol3 = priceMat.group(4);
				String discount = priceMat.group(5);
				String discountPrice = priceMat.group(6);
				priceMap.put("mid", mid != null ? mid : "");
				priceMap.put("mName", mName != null ? mName : "");
				priceMap.put("price", price != null ? price : "");
				priceMap.put("discount", discount != null ? discount : "");
				priceMap.put("discountPrice", discountPrice != null ? discountPrice : "");
				priceMap.put("isaCol3", isaCol3 != null ? isaCol3 : "");
				priceList.add(priceMap);
			}
			//获取其他优惠
			String otherRegx = "(?i)<td colspan=\"5\" class=\"other\">\\s*<em class=\"red2\">其他优惠：</em>(.*?)</td>";
			Pattern otherPat = Pattern.compile(otherRegx);
			Matcher otherMat = otherPat.matcher(aiTable);
			String otherPrice = "";
			if (otherMat.find()) {
				otherPrice = otherMat.group(1);
			}
			otherPrice = otherPrice != null ? otherPrice.replace("blue", "s-blue") : "";
			//组装新结构
			newAiTable.append("<div class=\"artMarketBox " + artMutClass + "\">")
					.append("<div class=\"artMarketBar\">")
					.append("<a href=\"").append("//m.pcauto.com.cn/auto/" + dealerid + "/\"").append(" class=\"aName\">").append("[" + agent +  "] " + dealname + "</a>")
					.append("<span class=\"area\">" + areaname + "/" + salesarea + "</span>")
					.append("</div>")
					.append("<ul class=\"artMarketList\">");
			for (Map<String,String> pricMap : priceList) {
				String askPriceUrl = "pcautobrowser://auto-ask-price/?" + "serialId=" + sgId + "&modelName=" + pricMap.get("mName") +
						"&dealerId=" + dealerid + "&dealerName=" + dealname + "&image=";
				String carLink = "pcautobrowser://model/"+ pricMap.get("mid") + "?serialId="+sgId+"&serialName=";
				newAiTable.append("<li>")
						.append("<a class=\"carLink\" href=\"" + carLink + "/\">")
						.append("<span class=\"carName\">" + pricMap.get("mName")  + "</span>")
						.append("<span class=\"carPris\"><i class=\"curPri\">" + pricMap.get("discountPrice") + "</i><i class=\"oldPri" + pricMap.get("isaCol3") + "\">"
								+ pricMap.get("price") + "</i><i class=\"reducePri\">" + pricMap.get("discount") +"</i></span>")
						.append("</a>")
						.append("<a class=\"btn-xdj\" href=\"" + askPriceUrl + "\">询底价</a>")
						.append("</li>");
			}
			newAiTable.append("</ul>");
			if (!StringUtils.isBlank(otherPrice)) {
				newAiTable.append("<div class=\"artMarketOther\">")
						.append("<span class=\"s-red\">其他优惠：</span>" + otherPrice)
						.append("</div>");
			}
			if (!StringUtils.isBlank(artMutClass)) {
				newAiTable.append("<div class=\"artMarketBtn\"><i>展开查看全部车型</i></div>");
			}
			newAiTable.append("</div>");
		}
		return newAiTable.toString();
	}

	public String change4AiCmt(String aiCmt) {
		StringBuilder newAiCmt = new StringBuilder();
		//获取车系Id
		String sgId = aiCmt.replaceAll("(?i).*\\ssgId=\"([^\"]+)\".*", "$1");
		String sgName = aiCmt.replaceAll("(?i).*\\ssgName=\"([^\"]+)\".*", "$1");
		//这里直接请求接口获取相关信息
		String cmtUrl = "http://price.pcauto.com.cn/comment/interface/auto/serial/get_comment_jh_json.jsp?sgid=" + sgId;
		try {
			if (!StringUtils.isBlank(sgId)) {
				//String cmtStr = cn.pconline.cms5.util.StringUtils.readHtml4Get(cmtUrl, cn.pconline.cms5.util.StringUtils.DEFAULT_PROXY_CONFIG);
				String cmtStr = ""; //获取cmt的内容
				if (!StringUtils.isBlank(cmtStr)) {
//					JSONObject cmtObj = JSONObject.parseObject(cmtStr);
//					int accountId = cmtObj.getIntValue("accountId");
					Map<String, Object> cmtObj = JsonUtils.jsonToObj(cmtStr, new TypeReference<Map<String, Object>>() {
					});
					int accountId = (int) cmtObj.get("accountId");
					if (accountId == 0) {
						return "";
					}
					String imgUrl = HtmlCMSUtils.face(accountId,"http://i6.3conline.com/images/upload/upc/face","50x50");
					String cmtName = String.valueOf(cmtObj.get("account"));
					String score = String.valueOf(cmtObj.get("averageScore"));
					String price = String.valueOf(cmtObj.get("price"));
					String mId = String.valueOf(cmtObj.get("modelId"));
					String mName = String.valueOf(cmtObj.get("modelName"));
					String oil = String.valueOf(cmtObj.get("oil"));
					String advantage = String.valueOf(cmtObj.get("advantage"));
					String disadvantage = String.valueOf(cmtObj.get("disadvantage"));
					String moreCommentlLink4wap = String.valueOf(cmtObj.get("moreCommentlLink4wap"));
					moreCommentlLink4wap = "pcautobrowser://serial-carowner-commenlist/?carSerialId=" + mId +"&pageCounterId=3968&serialId=" + sgId;
					String commentDetailLink4wap = String.valueOf(cmtObj.get("commentDetailLink4wap"));
					commentDetailLink4wap = "pcautobrowser://model-comment/?commentId=" + commentDetailLink4wap.replaceAll(".*?view_(.*?).html", "$1")
							+ "&carSerialId=" + mId + "&serialId=" + sgId + "&modelName=" + mName;
					if (advantage.length() > 73) {
						advantage = advantage.substring(0,73) + "...";
					}
					if (disadvantage.length() > 73) {
						disadvantage = disadvantage.substring(0,73) + "...";
					}
					newAiCmt.append("<div class=\"carReviewBox\">")
							.append("<a class=\"carReviewUser\" href=\"pcaction://user-center/" + accountId + "\">")
							.append("<img src=\"").append(imgUrl).append("\" alt=\"" + cmtName + "\">")
							.append("<span class=\"userName\">" + cmtName+ "</span>")
							.append("<span class=\"time\"></span>")
							.append("</a>")
							.append("<a class=\"carName\" href=\"" + commentDetailLink4wap + "\">").append("<em class=\"tag\">精</em>").append(mName).append("</a>")
							.append("<div class=\"carReviewInfo\">")
							.append("<span class=\"score\">评分：<em>" + score + "</em></span>")
							.append("<span class=\"pri\">裸车价：<em>" + price + "万</em></span>")
							.append("<span class=\"oil\">油耗：<em>" + oil + "/100KM</em></span>")
							.append("</div>")
							.append("<div class=\"des\"><span>优点</span>" + advantage + "</div>")
							.append("<div class=\"des\"><span>缺点</span>" + disadvantage + "</div>")
							.append("<a class=\"more\" href=\"" + moreCommentlLink4wap + "\"><i>查看更多" + sgName+ "车主点评</i></a>")
							.append("</div>");
				}
			}

		} catch(Exception e) {
			System.out.println("智能点评转换异常");
			e.printStackTrace();
		}
		return newAiCmt.toString();
	}

	static {
		DEFAULT_TAG_HANDLER_MAP.put("a", A_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("img", IMG_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("br", BLOCK_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("div", DIV_LIVE_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("p", KEEP_IN_TABLE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("table", TABLE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("tr", TR_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("td", TD_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("th", KEEP_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("script", REMOVE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("form", REMOVE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("epro_product1_js", REMOVE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("epro_product2_js", REMOVE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("epro_product3_js", REMOVE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("epro_product4_js", REMOVE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("epro_product5_js", REMOVE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("epro_product6_js", REMOVE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("epro_product7_js", REMOVE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("epro_soft_ad", REMOVE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("temptagamigopcqh", REMOVE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("style", REMOVE_TAG_HANDLER);
		DEFAULT_TAG_HANDLER_MAP.put("embed", EMBED_TAG_HANDLER);
	}

	public static class Tag {
		private String name="";
		private String text;
		private String textLow;
		private int attrStart = 0;
		private boolean begin = true;

		public Tag(String text) {
			this.text = text;
			this.textLow = text.toLowerCase();
		}

		public String getName() {
			if (StringUtils.isBlank(name) ) {
				int pos1 = text.indexOf(' ');
				int pos2 = text.indexOf('\t');
				int pos3 = text.indexOf('\n');

				int pos = -1;
				if (pos1 > 0) pos = pos1;
				if (pos2 > 0 && pos2 < pos)  pos = pos2;
				if (pos3 > 0 && pos3 < pos)  pos = pos3;

				int start = 1;
				if(text.length() <= 1){
					return name;
				}
				if (text.charAt(1) == '/') {
					start = 2;
					begin = false;
				}
				if (pos < 1) {
					name = text.substring(start, text.length() - 1);
				} else {
					name = text.substring(start, pos);
					if (start == 1) {
						attrStart = pos;
					}
				}
				name = name.toLowerCase().replaceAll("/$", "");//修正<br/>
			}
			return name;
		}

		public boolean isBegin() {
			return begin;
		}

		public String getAttr(String attr) {
			if (attrStart == 0) return null;

			int pos = textLow.indexOf(attr + "=", attrStart);
			if (pos > 0) {
				pos = pos + attr.length() + 1;
				int ch = text.charAt(pos);
				if (ch == '\'' || ch == '\"') {
					int pos2 = text.indexOf(ch, pos + 1);
					return (pos2 == -1? text :text.substring(pos + 1, pos2));
				} else {
					int pos2 = text.indexOf(' ', pos + 1);
					if (pos2 == -1) pos2 = text.indexOf('/', pos + 1);
					if (pos2 == -1) pos2 = text.indexOf('>', pos + 1);
					return text.substring(pos, pos2);
				}
			}

			return null;
		}

		public List<String>  getAttrs() {
			List<String> items=new ArrayList<String>();
			if (attrStart == 0) return items;

			String regex = "\\s+(\\w+)\\s*=";
			Matcher matcherAttr = Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(textLow);
			while (matcherAttr.find()){
				String item=matcherAttr.group(1);
				items.add(item);
			}
			return items;
		}

	}

	public static String getSiteName(){
		return siteName;
	}

	public static boolean isColorDark(String color) {
		if (color == null || color.length() != 7) {
			return false;
		}

		if (color.charAt(0) != '#') {
			return false;
		}

		int r = (hex2int(color.charAt(1)) << 4) + hex2int(color.charAt(2));
		int g = (hex2int(color.charAt(3)) << 4) + hex2int(color.charAt(4));
		int b = (hex2int(color.charAt(5)) << 4) + hex2int(color.charAt(6));

		double y = 0.299 * r + 0.587 * g + 0.114 * b;

		return y < 122.0;
	}

	private static int hex2int(char c) {
		switch (c) {
			case '0': return 0;
			case '1': return 1;
			case '2': return 2;
			case '3': return 3;
			case '4': return 4;
			case '5': return 5;
			case '6': return 6;
			case '7': return 7;
			case '8': return 8;
			case '9': return 9;
			case 'A': return 10;
			case 'a': return 10;
			case 'B': return 11;
			case 'b': return 11;
			case 'C': return 12;
			case 'c': return 12;
			case 'D': return 13;
			case 'd': return 13;
			case 'E': return 14;
			case 'e': return 14;
			case 'F': return 15;
			case 'f': return 15;
		}
		return 0;
	}

}
